package com.bdqn.ch06.service;

import com.bdqn.ch06.entity.Role;
import com.bdqn.ch06.entity.User;
import com.bdqn.ch06.repository.UserRepository;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(value = "userServiceImp")
public class UserServiceImp implements UserService {

    @Resource
    UserRepository userRepository;

    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (param.get("usrName") != null && !param.get("usrName").equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
                }
                if (param.get("roleId") != null && !param.get("roleId").toString().equals("0")) {
                    Role role = new Role();
                    role.setRoleId(Long.valueOf(param.get("roleId").toString()));
                    predicates.add(criteriaBuilder.equal(root.get("role"), role));
                }
                /*if (param.get("usrFlag") != null) {
                    predicates.add(criteriaBuilder.equal(root.get("usrFlag"), param.get("usrFlag")));
                }*/
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
    }

    @Override
    public User findByUserNameBiz(String uname) {
        return userRepository.findUserByUsrName(uname);
    }

    @Override
    //@Cacheable(value = "user", keyGenerator = "keyGenerator")
    //@CachePut(value = "user", keyGenerator = "keyGenerator")
    @CacheEvict(value = "user", keyGenerator = "keyGenerator")
    public List<User> getUserListBiz() {
        return userRepository.findAll();
    }

    @Override
    public void deleteByIdBiz(Long id) {
        try {
            userRepository.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveUser(User user) {
        userRepository.save(user);
    }

    @Override
    public User getByUserId(Long id) {
        return userRepository.findById(id).get();
    }
}
